<?php

class CaptchaHelper {
	
	const SECURITY_KEY = 'wdlst';
	const SECURITY_CODE_EXPIRE = 1800;
	
	/**
	 * 加密验证码
	 * 
	 * @param string $str
	 */
	public static function generateCoce($str) {
        $key = substr(md5(self::SECURITY_KEY), 5, 8);
        $str = substr(md5($str), 8, 10);
        return md5($key . $str);
	}
	
	public static function generateKey() {
		return self::generateCoce(self::SECURITY_KEY);
	}
	
	/**
	 * 验证验证码
	 * 
	 * @param string $code
	 */
	public static function verify($code) {
        $key = self::generateKey();
        
        // get from session
        $secode = Session::get($key);
        
        // $secode = ...
        if(empty($code) || empty($secode)) {
            return false;
        }
        
        // session 过期
        if(time() - $secode['time'] > self::SECURITY_CODE_EXPIRE) {
        	Session::forget($key);
        	return false;
        }

        if(self::generateCoce(strtoupper($code)) == $secode['code']) {
            Session::forget($key);
            return true;
        }

        return false;
	}
}